/*
 * @Author       : Zeepunt.H
 * @Date         : 2022-03-12 13:15:02
 * @LastEditTime : 2022-07-17 20:22:50
 * Gitee : https://gitee.com/zeepunt
 * Github: https://github.com/Recaa
 *  
 * Copyright (c) 2022 by Zeepunt.H, All Rights Reserved. 
 */

#include <common.h>

static pthread_t lvgl_tid;
static pthread_t lvgl_timer_tid;
static pthread_mutex_t lvgl_mutex;

void lvgl_demo(void)
{
    lv_obj_t *obj = lv_obj_create(lv_scr_act());
	lv_obj_set_pos(obj, 0, 0);
	lv_obj_set_size(obj, lv_disp_get_hor_res(NULL), lv_disp_get_ver_res(NULL));

    lv_obj_t *label = lv_label_create(obj);
	lv_label_set_text(label, "Hello, LVGL.");
    lv_obj_center(label);
}

static void* lvgl_entry(void *arg)
{
    int ret = -1;
    
    /* 初始化 lvgl */
    lv_init();

    /* 设备初始化 */
    lv_port_disp_init();
    lv_port_indev_init();
    lv_port_fs_init();
    lv_port_font_init(24);

    pthread_mutex_unlock(&lvgl_mutex);

    while (1) 
    {
        /* 周期性调用 lv_timer_handler */
        lv_timer_handler();
        /* 官方建议是最少 5ms */
        usleep(5 * 1000);
    }
}

static void* lvgl_timer_entry(void *arg)
{
    while (1)
    {
        usleep(5 * 1000);
        /* tick 单位是 ms */
        lv_tick_inc(5);
    }
}

int main(void)
{
    int ret = -1;

    ret = pthread_mutex_init(&lvgl_mutex, NULL);
    if (ret < 0)
    {
        LOG_ERROR("mutex init fail.");
        goto exit;
    }
    pthread_mutex_lock(&lvgl_mutex);

    ret = pthread_create(&lvgl_tid, NULL, lvgl_entry, NULL);
    if (0 == ret)
    {
        pthread_detach(lvgl_tid);   
    }
    else
    {
        LOG_ERROR("lvgl_entry thread crate fail: %d.", ret);
    }

    pthread_mutex_lock(&lvgl_mutex);
    pthread_mutex_unlock(&lvgl_mutex);
    pthread_mutex_destroy(&lvgl_mutex);

    ret = pthread_create(&lvgl_timer_tid, NULL, lvgl_timer_entry, NULL);
    if (0 == ret)
    {
        pthread_detach(lvgl_timer_tid);   
    }
    else
    {
        LOG_ERROR("lvgl_timer_entry thread crate fail: %d.", ret);
    }
    
    /* app */
    lvgl_demo();

    while(1);

    ret = 0;
exit:
    lv_port_disp_deinit();
    
    return ret;
}